let mcScore = null;
let curNote = null;
let enableJsBridge = true;
let scoreId = -1;
let mJsBridge = null
let mScoreKeep = null
$(function () {
	$('.loading .wrap').css('display', 'block');
	scoreId = GetQueryString("songid");
	init()
})
function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return unescape(r[2]);
	return null;
}

function onNoteClick(note) {
	console.log('onNoteClick  note='+JSON.stringify(note))
	if(curNote) {
		curNote.element.setAttribute('fill', 'black');
	}
	note.element.setAttribute('fill', 'green');
	// mcScore.pointToNote(note);
	curNote = note;
	mJsBridge.callHandler('McBridger_onNoteClick',JSON
		.stringify({on_tick:note.ontick,off_tick:note.offtick},null))
}
function onNoteOn(note) {
	// totalNotes++;
	// console.log('cbjcbj onNoteOn:'+JSON.stringify(note.pitch))
	if(note.staff == 0) {
		//note.element.setAttribute('fill', '#7acad1');

		note.element.setAttribute('fill', '#7acad1');
		// keyboard.lightUp(pitchToKey(note.pitch), '#7acad1');
		//keyboard.lightUp(pitchToKey(note.pitch), '#ffc90f');
	} else if (note.staff == 1) {
		//note.element.setAttribute('fill', '#d74e4e');
		//note.element.setAttribute('fill', '#f0396d');

		note.element.setAttribute('fill', '#ffc90f');
		// keyboard.lightUp(pitchToKey(note.pitch), '#ffc90f');
	}
	// curNote = note;
	// if(mode != "listen"){ //欣赏模式不要打分
	// 	scoreKeeper.noteOn(note);
	// }
}
function onNoteOff(note) {
	// console.log('cbjcbj onNoteOff:'+JSON.stringify(note.pitch))
	note.element.setAttribute('fill', 'black');
	// keyboard.lightOff(pitchToKey(note.pitch));
	// if(mode != "listen"){
	// 	scoreKeeper.noteOff(note);
	// }
}

function onNoteError(note) {
	note.element.setAttribute('fill', 'red');
}

function onNoteCorrect(note) {
	note.element.setAttribute('fill', 'green');
}

function onFinish(){
	// clearInterval(interval);
	// console.log("===========  finish");
	// stop();
	//
	// var sc = scoreKeeper.score();
	// console.log("score: " + JSON.stringify(sc));
	// //scoreKeeper.clean();
	// if(mode != 'listen') {
	// 	$('#res_score').text(Math.round(sc.score*100));
	// 	$('#hitrtio').text(Math.round(sc.hit_dur*100));
	// 	$('#hitrate').text(Math.round(sc.hit_num*100));
	// 	//$('#result').show();
	// 	if(mode == 'pk'){
	// 		sendEtude(Math.round(sc.score*100), Math.round(sc.hit_dur*100), Math.round(sc.hit_num*100));
	// 	}
	// 	$('#result').css('display', 'block');
	// }
}

function onError(msg) {
	//alert(msg);
}

function onScoreReady() {
	$('.loading').css('display', 'none');
/*
	McClass.createNew(function(obj){
		mcClass = obj;
		mcClass.setOnUserKeyDown(keyDown);
		mcClass.setOnUserKeyUp(keyUp);

		$('#connect').bind('touchend', function(){
			mcClass.connect(function (responseData){
				console.log("connect return "+responseData);
				if(responseData == "true"){
					$('#connect').css('display', 'none');
					$('#disconnect').css('display', 'block');
				}
			});
		});

		$('#disconnect').bind('touchend', function(){
			mcClass.disconnect(function (responseData){
				console.log("disconnect return "+responseData);
				if(responseData == "false"){
					$('#disconnect').css('display', 'none');
					$('#connect').css('display', 'block');
				}
			});
		});
	});

	var showBPMPanel = true;

	initScore();
	handlerJsBridge();




	$('#bpmChange').bind('touchend', function() {
		if(showBPMPanel) {
			if(isPlay) {
				pause();
				isPause = true;
			}
			$(this).addClass('active');
			showBPMPanel = false;
			$('.panel_speed').show();
			$('#bpm').text($('#bpmRange').val() + 'bpm');
		} else {
			$(this).removeClass('active');
			showBPMPanel = true;
			$('.panel_speed').hide();

			console.log("set BPM "+parseInt($('#bpmRange').val()));
			mcScore.setBPM(parseInt($('#bpmRange').val()));
			totalTime = mcScore.getTotalRealTime();

			if(isPause) {
				play();
				isPause = false;
			}
		}
	});

	$('#bpmRange').bind("input", function() {
		$('#bpm').text($('#bpmRange').val() + 'bpm');
	});

	$('#bpmReduce').bind('touchend', function() {
		var current = parseInt($('#bpmRange').val());
		$('#bpmRange').val(current - 1);
		$('#bpm').text($('#bpmRange').val() + 'bpm');
	});

	$('#bpmRaise').bind('touchend', function() {
		var current = parseInt($('#bpmRange').val());
		$('#bpmRange').val(current + 1);
		$('#bpm').text($('#bpmRange').val() + 'bpm');
	});


	$(window).bind('unload', function() {
		stop();
	});
*/
}

function registerHandler() {
	mJsBridge.registerHandler('McBridger_midiPlay',function (data,cb) {
		console.log('java call McBridger_midiPlay data='+JSON.stringify(data))
		// mJsBridge.callHandler('McMidiPlayer_start','',function (res) {
		//
		// })
		mcScore.status = 'PLAYING'
	})
	mJsBridge.registerHandler('McBridger_pause',function (data,cb) {
		mcScore.status = 'PAUSE'
	})
	mJsBridge.registerHandler('McBridger_stop',function (data,cb) {
		mcScore.status = 'INIT'
	})

	mJsBridge.registerHandler('McMidiPlayer_onFinish',function (data,cb) {
		mcScore.status = 'INIT'
	})

	mJsBridge.registerHandler('McBridger_midiNoteOn',function (data,cb) {
		let jsonObj = JSON.parse(data)
		mcScore.nextMidiFrame(jsonObj)
		cb('')
	})

	mJsBridge.registerHandler('McBridger_midiNoteOff',function (data,cb) {
		let jsonObj = JSON.parse(data)
        mcScore.lastMidiOff(jsonObj)
	})

	// mJsBridge.registerHandler('McBridger_restart',function (data,cb) {
	// 	mJsBridge.callHandler('McMidiPlayer_start','',function (res) {
	//
	// 	})
	// })

	mJsBridge.registerHandler('McBridger_clearScore',function (data,cb) {
		mScoreKeep.clean()
	})

	mJsBridge.registerHandler('McBridger_midiNoteError',function (data,cb) {
		let jsonObj = JSON.parse(data)
		mcScore.errorClick(jsonObj)
	})

	mJsBridge.registerHandler('McBridger_midiNoteCorrect',function (data,cb) {
		let jsonObj = JSON.parse(data)
		mcScore.correctClick(jsonObj)
	})

	mJsBridge.registerHandler('McBridger_midiUserKeyDown',function (data,cb) {
		let jsonObj = JSON.parse(data)
		mcScore.userNoteOn(jsonObj)
	})

	mJsBridge.registerHandler('McBridger_midiUserKeyUp',function (data,cb) {
		let jsonObj = JSON.parse(data)
		mcScore.userNoteOff(jsonObj)
	})

	mJsBridge.registerHandler('McBridger_midiNotePkOff',function (data,cb) {
		let jsonObj = JSON.parse(data)
		mcScore.pkMidiOff(jsonObj)
	})

	mJsBridge.registerHandler('McBridger_midiCalcScore',function (data,cb) {
		cb(mScoreKeep.score())
	})

	mJsBridge.registerHandler('McBridger_audioLoop_A',function (data,cb) {
		mcScore.setA(curNote)
		cb(JSON.stringify({res:true,msg:''}))
	})
	mJsBridge.registerHandler('McBridger_audioLoop_B',function (data,cb) {
		mcScore.setB(curNote)
		cb(JSON.stringify({res:true,msg:''}))
	})
	mJsBridge.registerHandler('McBridger_loopCancel',function (data,cb) {
		mcScore.cancelLoop()
	})
}


function init() {
	var option = {
		enableJsBridge: enableJsBridge,
		onNoteClick: onNoteClick, //绑定用户点击某个音符后执行的回调，设定AB循环时要用这个
		onNoteOn: onNoteOn, //绑定某个音符触发(开始发声)后执行的回调，与seek方法配合可实现任意区间循环
		onNoteOff: onNoteOff,
		onFinish: onFinish,
		onError: onError,
		onReady: onScoreReady, //绑定乐谱资源加载完毕后执行的回调
		onNoteError:onNoteError,
		onNoteCorrect:onNoteCorrect,
	};
	mScoreKeep = McScoreKeeper.createNew()
	mcScore = McScore.createNew(option);
	mcScore.init(scoreId);
	mcScore.setScoreKeep(mScoreKeep)
	McJsBridge.createNew(function (bridge) {
		mJsBridge = bridge
		registerHandler()
	})



}
